// 文件路径: com.huaxin.device.service.impl.DeviceAlarmConfigServiceImpl.java
package com.huaxin.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.device.dto.ResponseCode;
import com.huaxin.device.dto.ResponseResult;
import com.huaxin.device.dto.request.DeviceAlarmConfigCreateReqDTO;
import com.huaxin.device.dto.request.DeviceAlarmConfigPageListReqDTO;
import com.huaxin.device.dto.request.DeviceAlarmConfigUpdateReqDTO;
import com.huaxin.device.mapper.DeviceAlarmConfigMapper;
import com.huaxin.device.mapping.DeviceAlarmConfigMapping;
import com.huaxin.device.models.DeviceAlarmConfig;
import com.huaxin.device.service.DeviceAlarmConfigService;
import lombok.RequiredArgsConstructor;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.webjars.NotFoundException;

import java.util.List;

import static org.springframework.util.StringUtils.hasText;

@Service
@RequiredArgsConstructor
public class DeviceAlarmConfigServiceImpl extends ServiceImpl<DeviceAlarmConfigMapper, DeviceAlarmConfig>
        implements DeviceAlarmConfigService {

    private final ApplicationContext applicationContext;
    private final DeviceAlarmConfigMapping mapping; // 假设存在映射工具

    @Override
    public ResponseResult<DeviceAlarmConfig> create(DeviceAlarmConfigCreateReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }

        // 检查 deviceId 是否已存在配置
        LambdaQueryWrapper<DeviceAlarmConfig> existsWrapper = new LambdaQueryWrapper<>();
        existsWrapper.eq(DeviceAlarmConfig::getDeviceId, in.getDeviceId());
        if (this.exists(existsWrapper)) {
            return ResponseResult.failure(ResponseCode.CUSTOM_BUSINESS_ERROR, "设备 [" + in.getDeviceId() + "] 已存在报警配置", null);
        }

        DeviceAlarmConfig entity = mapping.toEntity(in);
        if (!this.save(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "添加失败，请稍后再试！", null);
        }

        DeviceAlarmConfig created = this.getByConfigId(entity.getId());
        return ResponseResult.ok(created);
    }

    @Override
    public DeviceAlarmConfig getByConfigId(String id) {
        if (StringUtils.isBlank(id)) {
            throw new IllegalArgumentException("ID不能为空");
        }
        DeviceAlarmConfig entity = this.getById(id);
        if (entity == null) {
            throw new NotFoundException("设备报警配置不存在");
        }
        return entity;
    }

    @Override
    public ResponseResult<String> update(DeviceAlarmConfigUpdateReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }

        DeviceAlarmConfig entity = this.getByConfigId(in.getId());
        mapping.updateEntity(in, entity); // 映射更新字段

        if (!this.updateById(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "更新失败，请稍后再试！", null);
        }
        return ResponseResult.ok("更新成功");
    }

    @Override
    public ResponseResult<String> delete(String id) {
        DeviceAlarmConfig entity = this.getByConfigId(id);

        // 只有在禁用状态下才允许删除
        if (Boolean.TRUE.equals(entity.getIsEnabled())) {
            return ResponseResult.failure(ResponseCode.CUSTOM_BUSINESS_ERROR, "启用状态不允许删除", null);
        }

        boolean removed = this.applicationContext.getBean(DeviceAlarmConfigService.class).removeById(id);
        if (!removed) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "删除失败，请稍后重试", null);
        }
        return ResponseResult.ok("删除成功！");
    }

    @Override
    public ResponseResult<String> enable(String id) {
        DeviceAlarmConfig entity = this.getByConfigId(id);
        entity.setIsEnabled(true);
        if (!this.updateById(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "启用失败，请稍后再试！", null);
        }
        return ResponseResult.ok("启用成功");
    }

    @Override
    public ResponseResult<String> disable(String id) {
        DeviceAlarmConfig entity = this.getByConfigId(id);
        entity.setIsEnabled(false);
        if (!this.updateById(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "禁用失败，请稍后再试！", null);
        }
        return ResponseResult.ok("禁用成功！");
    }

    @Override
    public ResponseResult<IPage<DeviceAlarmConfig>> pageQuery(DeviceAlarmConfigPageListReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }

        IPage<DeviceAlarmConfig> page = new Page<>(in.getPageNum(), in.getPageSize());
        LambdaQueryWrapper<DeviceAlarmConfig> wrapper = new LambdaQueryWrapper<>();

        // 按设备实例ID过滤
        if (hasText(in.getDeviceId())) {
            wrapper.eq(DeviceAlarmConfig::getDeviceId, in.getDeviceId());
        }

        // 按组织家族过滤
        if (hasText(in.getFamilyId())) {
            wrapper.eq(DeviceAlarmConfig::getFamilyId, in.getFamilyId());
        }

        // 按启用状态过滤
        if (in.getIsEnabled() != null) {
            wrapper.eq(DeviceAlarmConfig::getIsEnabled, in.getIsEnabled());
        }

        // 按创建时间倒序
        wrapper.orderByDesc(DeviceAlarmConfig::getCreatedAt);

        IPage<DeviceAlarmConfig> resultPage = this.page(page, wrapper);
        return ResponseResult.ok(resultPage);
    }

    @Override
    public List<DeviceAlarmConfig> getAllEnabled() {
        LambdaQueryWrapper<DeviceAlarmConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceAlarmConfig::getIsEnabled, true);
        return this.list(wrapper);
    }

    @Override
    public DeviceAlarmConfig getByDeviceId(String deviceId) {
        LambdaQueryWrapper<DeviceAlarmConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceAlarmConfig::getDeviceId, deviceId);
        return this.getOne(wrapper);
    }

    @Override
    public List<String> getDeviceIdsByTemplate(String templateId) {
        LambdaQueryWrapper<DeviceAlarmConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceAlarmConfig::getTemplateId, templateId);
        return this.list(wrapper).stream().map(DeviceAlarmConfig::getDeviceId).toList();
    }
}